package com.hyg.ndkapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * Author: HuangYuGuang
 * Date: 2024/3/14
 */
public class RangingActivity extends AppCompatActivity implements View.OnClickListener{
    private String TAG = RangingActivity.class.getSimpleName();

    TextView tv_seri;

    public Handler mHandler = new Handler();
    private volatile boolean isStart = false;
    private LightRanging.MeasuredHeightCallback measuredHeightCallback;

    public static void launch(Activity from){
        from.startActivity(new Intent(from, RangingActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranging);

        tv_seri = findViewById(R.id.tv_seri);
        findViewById(R.id.btn0).setOnClickListener(this);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn0:
                new I2CTask(true).execute();
                break;
            case R.id.btn1:
                startJNI();
                break;
            case R.id.btn2:
                stopJNI();
                break;
        }
    }

    private void stopJNI(){
        if(isStart){
            isStart = false;
            LightRanging.getInstance().release();
        }
    }

    private void addTestLog(String msg){
        if(tv_seri.getLineCount() > 300){
            tv_seri.setText(String.format("%s\n", msg));
        }else {
            tv_seri.append(String.format("%s\n", msg));
        }
    }

    private void startJNI(){
        if(isStart) return;
        isStart = true;
        measuredHeightCallback = new LightRanging.MeasuredHeightCallback() {
            @Override
            public void onHeight(Integer[] heights) {
                String h = String.format("h1 = %s, h2 = %s, h3 = %s",heights[0],heights[1],heights[2]);
                addTestLog(h);
            }

            @Override
            public void onHeightError(String msg) {
                addTestLog(msg);
                isStart = false;
            }
        };
        LightRanging.getInstance().startJni(measuredHeightCallback);
    }

    class I2CTask extends AsyncTask<String, String, String> {

        boolean isDetail = false;

        public I2CTask(boolean isDetail) {
            this.isDetail = isDetail;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            addTestLog(values[0]);
        }

        @Override
        protected String doInBackground(String... strings) {
            if(isStart){
                isStart = false;
                LightRanging.getInstance().release();
                SystemClock.sleep(300);
            }
            try { // 设置I2C从设备地址
                /**
                 * 查询I2C已连接设备的地址
                 * result=0, successMsg=     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f00:          -- -- -- -- -- -- -- -- -- -- -- -- UU 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- UU -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: 70 -- -- -- -- -- -- --
                 */
                sendShellCmd("busybox i2cdetect -r -y 7");
//                /**
//                 * 选择通道1（通道值：1/2/4）
//                 */
//                sendShellCmd("busybox i2cset -f -y 7 0x70 0x01");
//                /**
//                 * 读取高位的值
//                 * result=0, successMsg=0x0410, errorMsg=
//                 * 值转换后为0X104,然后要右移四位二进制0x1040（除以16），再除以另一个值就得到距离
//                 */
//                sendShellCmd("busybox i2cget -f -y 7 0x40 0x5E w");
//                /**
//                 * 读取低位的值
//                 * result=0, successMsg=0x02, errorMsg=
//                 */
//                sendShellCmd("busybox i2cget -f -y 7 0x40 0x35 b");
//                doHeight();
                int height1 = 0;
                int height2 = 0;
                int height3 = 0;
                String msg = "";
                height1 = getMeasuredHeight(1, isDetail);
                Log.e(TAG,msg = String.format("h1 = %s, h2 = %s, h3 = %s",height1, height2, height3));
                publishProgress(msg);
                height2 = getMeasuredHeight(2, isDetail);
                Log.e(TAG,msg = String.format("h1 = %s, h2 = %s, h3 = %s",height1, height2, height3));
                publishProgress(msg);
                height3 = getMeasuredHeight(4, isDetail);
                Log.e(TAG,msg = String.format("h1 = %s, h2 = %s, h3 = %s",height1, height2, height3));
                publishProgress(msg);
            } catch (Exception e) {
                e.printStackTrace();
                publishProgress(e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
        }
    }

    private void sendShellCmd(String cmd){
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmd,true);
        Log.e(TAG,String.format("-> %s\n<- result=%s, successMsg=%s, errorMsg=%s",cmd, commandResult.result,commandResult.successMsg,commandResult.errorMsg));
    }

    /**
     * 获取测量的高度
     * @param channel 三个传感器，三个通道（1/2/4）
     * @return 高度mm,大于630的数据是超限的数据，不能用，小于25mm也测不了
     */
    private int getMeasuredHeight(int channel, boolean isDetail) throws Exception {
//        Log.d(TAG, "选择通道" + channel);
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(String.format("busybox i2cset -f -y 7 0x70 %s",channel),true);
        if(commandResult.result != 0) throw new  Exception("i2cset 0x70 " + channel +","+ commandResult.errorMsg);
        SystemClock.sleep(20);

//            Log.d(TAG, "获取0x5E数据");
        commandResult = ShellUtils.execCmd("busybox i2cget -f -y 7 0x40 0x5E w",true);
        if(commandResult.result != 0) throw new  Exception("i2cget 0x40 0x5E " + commandResult.errorMsg);
        String result1 = commandResult.successMsg; //0x0410
        if(isDetail){
            String finalResult = result1;
            mHandler.post(() -> addTestLog(String.format("通道%s，0x5E的值 = %s",channel, finalResult)));
        }

//            Log.d(TAG, "获取0x35数据");
        commandResult = ShellUtils.execCmd("busybox i2cget -f -y 7 0x40 0x35 b",true);
        if(commandResult.result != 0) throw new  Exception("i2cget 0x40 0x35 " + commandResult.errorMsg);
        String result2 = commandResult.successMsg; //0x02
        if(isDetail){
            String finalResult = result2;
            mHandler.post(() -> addTestLog(String.format("通道%s，0x35的值 = %s",channel, finalResult)));
        }

//            Log.d(TAG, "开始计算");
        if(result1.length() == 6 && result2.length() == 4){
            result1 = String.format("%s%s",result1.substring(4),result1.charAt(3));
            float value = Integer.parseInt(result1,16);
            int n = Integer.parseInt(result2.substring(2),16);
            return (int) (value / 16 / (1 << n) * 10);
        }else {
            return 640;
        }
    }
}
